package com.sqllog.admin.framework.tools;

import com.sqllog.admin.auth.domain.User;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;


/**
 * Security 工 具 类
 *
 * @author chennengcheng
 * @date 2022-01-07 17:19
 * @remark
 */

public class SecurityUtil {

    /**
     * 获取当前登录用户的信息，如果未登录返回null
     *
     * @return Object 当前登录用户
     */
    public static User currentUser() {
        return null!=getAuthentication()?(User) getAuthentication().getPrincipal():null;
    }

    /**
     * 获取当前登录用户的信息
     * @return
     */
    public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return !(authentication instanceof AnonymousAuthenticationToken)?authentication:null;
//        if (!(authentication instanceof AnonymousAuthenticationToken))
//            return authentication;
//        return null;
    }

    /**
     * 验证当前用户是否登录
     *
     * @return boolean 是否登录
     */
    public static boolean isAuthentication() {
        // if security session eq s-id is not null to index
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return !(auth instanceof AnonymousAuthenticationToken);
    }


}
